//
//  ExtraLoadDataViewController.m
//  sdkDemo
//
//  Created by ChuanYou Xie on 2023/8/1.
//  Copyright © 2023 qqconnect. All rights reserved.
//

#import "ExtraLoadDataViewController.h"
#import "SDKCall.h"
#import "QQAPIShareEntry.h"

static NSInteger const ExtraLoadDataTag_Url       = 10200;
static NSInteger const ExtraLoadDataTag_JsonString = 10201;
static NSInteger const ExtraLoadDataTag_Method = 10202;

#pragma mark - ExServiceCellModel
@interface ExtraLoadDataCellModel : NSObject

@property (nonatomic, assign) int cellTag;
@property (nonatomic, copy) NSString *cellKey;
@property (nonatomic, copy) NSString *cellValue;

+ (ExtraLoadDataCellModel *)createCellModelForTag:(int)tag key:(NSString *)key value:(NSString *)value;
- (CGFloat)cellHeight;

@end

@implementation ExtraLoadDataCellModel

+ (ExtraLoadDataCellModel *)createCellModelForTag:(int)tag key:(NSString *)key value:(NSString *)value {
    ExtraLoadDataCellModel *resultModel = [ExtraLoadDataCellModel new];
    resultModel.cellTag = tag;
    resultModel.cellKey = key;
    resultModel.cellValue = value;
    return resultModel;
}

- (CGFloat)cellHeight {
    if (self.cellTag == ExtraLoadDataTag_JsonString) {
        return 120;
    }
    if (self.cellTag == ExtraLoadDataTag_Method) {
        return 60;
    }
    return 100;
}

@end





#pragma mark - ExServiceTableCell

@interface ExtraLoadDataTableCell : UITableViewCell

@property (nonatomic, strong) ExtraLoadDataCellModel *cellModel;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UITextField *editTextfield;
@property (nonatomic, strong) UITextView *textView;

- (void)loadCellWithModel:(ExtraLoadDataCellModel *)cellInfo;
- (NSString *)textResult;

@end

@implementation ExtraLoadDataTableCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self.contentView addSubview:self.titleLabel];
        [self.contentView addSubview:self.editTextfield];
        [self.contentView addSubview:self.textView];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    CGFloat cellWidth = self.frame.size.width;
    CGFloat cellHeight = self.frame.size.height;
    self.titleLabel.frame = CGRectMake(10, (cellHeight-13)/2, 60, 13);
    
    CGFloat textTopMargin = 8;
    CGRect textFrame = CGRectMake(CGRectGetMaxX(_titleLabel.frame)+2.f, textTopMargin, cellWidth-CGRectGetMaxX(_titleLabel.frame)-15.f, cellHeight - (textTopMargin * 2));
    self.editTextfield.frame = textFrame;
    
    self.textView.frame = textFrame;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)loadCellWithModel:(ExtraLoadDataCellModel *)cellModel {
    self.cellModel = cellModel;
    self.titleLabel.text = cellModel.cellKey;
    
    if (cellModel.cellTag == ExtraLoadDataTag_JsonString || cellModel.cellTag == ExtraLoadDataTag_Url) {
        self.textView.text = cellModel.cellValue;
        [self addSubview:self.textView];
        [self.editTextfield removeFromSuperview];
    } else {
        self.editTextfield.text = cellModel.cellValue;
        [self addSubview:self.editTextfield];
        [self.textView removeFromSuperview];
    }
    [self setNeedsLayout];
}

- (NSString *)textResult {
    if (self.cellModel.cellTag == ExtraLoadDataTag_JsonString || self.cellModel.cellTag == ExtraLoadDataTag_Url) {
        return self.textView.text;
    }
    return self.editTextfield.text;
}

#pragma mark - Getter and setter

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 60, 60, 13)];
        _titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:12.f];
    }
    return _titleLabel;
}

- (UITextField *)editTextfield {
    if (!_editTextfield) {
        _editTextfield = [[UITextField alloc] init];
        _editTextfield.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14.f];
        _editTextfield.layer.borderWidth = 0.5f;
        _editTextfield.layer.borderColor = [UIColor grayColor].CGColor;
        _editTextfield.layer.cornerRadius = 3.0;
        _editTextfield.layer.masksToBounds = YES;
    }
    return _editTextfield;
}

- (UITextView *)textView {
    if (!_textView) {
        _textView = [[UITextView alloc] init];
        _textView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        _textView.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14.f];
        _textView.layer.borderWidth = 0.5f;
        _textView.layer.borderColor = [UIColor grayColor].CGColor;
        _textView.layer.cornerRadius = 3.0;
        _textView.layer.masksToBounds = YES;
    }
    return _textView;
}

@end







#pragma mark - ExtraServiceSettingViewController

@interface ExtraLoadDataViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *confirmButton;
@property (nonatomic, strong) UILabel *tipsLabel;
@property (nonatomic, strong) UITextView *resultTextView;

@property (nonatomic, copy) NSArray *dataSource;
@property (nonatomic, copy) NSString *url;
@property (nonatomic, copy) NSString *jsonString;
@property (nonatomic, copy) NSString *requestMethod;

@property (nonatomic, copy) NSOperationQueue *operationQueue;

@end

@implementation ExtraLoadDataViewController

- (instancetype)init {
    if (self = [super init]) {
        self.url = @"https://graphapi.testsite.woa.com/sougou/get_tofu_cubes";
        self.requestMethod = @"get";
        self.jsonString = @"{\"oauth_consumer_key\":\"102060558\"}";
        self.dataSource = [NSMutableArray arrayWithCapacity:0];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initData];
    self.navigationItem.title = @"加载json数据";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.resultTextView];
    [self.view addSubview:self.confirmButton];
    [self.view addSubview:self.tipsLabel];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapEvent:)];
    [self.view addGestureRecognizer:tap];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    CGFloat screenWidth = CGRectGetWidth(self.view.frame);
    CGFloat screenHeight = CGRectGetHeight(self.view.frame);
    CGFloat tipsLabelHeight = 60;
    CGFloat confirmButtonHeight = 44;
    CGFloat tableViewHeight = [self cellTotalHeight];
    CGFloat topHeight = self.navigationController.navigationBar.height + UIApplication.sharedApplication.statusBarFrame.size.height;
    self.tableView.frame = CGRectMake(0, topHeight, screenWidth, tableViewHeight);
    
    CGFloat resultTextViewHeight = screenHeight - tipsLabelHeight - confirmButtonHeight - tableViewHeight - 60 - topHeight;
    self.resultTextView.frame = CGRectMake(10, CGRectGetMaxY(self.tableView.frame) + 10, screenWidth - 20, resultTextViewHeight);
    
    self.confirmButton.frame = CGRectMake(20, screenHeight - confirmButtonHeight - 40, screenWidth - 40, confirmButtonHeight);
    self.tipsLabel.frame = CGRectMake(20, CGRectGetMinY(self.confirmButton.frame) - tipsLabelHeight - 10, screenWidth - 40, tipsLabelHeight);
}

#pragma mark - Public and privite methods

- (void)initData {
    NSMutableArray *cellModels = [NSMutableArray array];
    ExtraLoadDataCellModel *urlCellModel = [ExtraLoadDataCellModel createCellModelForTag:ExtraLoadDataTag_Url key:@"URL: " value:self.url];
    [cellModels addObject:urlCellModel];
    
    ExtraLoadDataCellModel *jsonStringCellModel = [ExtraLoadDataCellModel createCellModelForTag:ExtraLoadDataTag_JsonString key:@"Json参数: " value:self.jsonString];
    [cellModels addObject:jsonStringCellModel];
    
    ExtraLoadDataCellModel *methodCellModel = [ExtraLoadDataCellModel createCellModelForTag:ExtraLoadDataTag_Method key:@"Method: " value:self.requestMethod];
    [cellModels addObject:methodCellModel];
    
    self.dataSource = [cellModels copy];
}

- (CGFloat)cellTotalHeight {
    CGFloat cellTotalHeight = 0;
    for (ExtraLoadDataCellModel *cellModel in self.dataSource) {
        cellTotalHeight += [cellModel cellHeight];
    }
    return cellTotalHeight;
}

- (ExtraLoadDataCellModel *)cellModelWithRow:(NSInteger)row {
    if (self.dataSource.count <= row) {
        return nil;
    }
    return self.dataSource[row];
}

- (void)loadResult {
    for (NSInteger i = 0; i < self.dataSource.count; i++) {
        ExtraLoadDataTableCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        if (cell.tag == ExtraLoadDataTag_Url) {
            self.url = [cell textResult];
        }
        if (cell.tag == ExtraLoadDataTag_JsonString) {
            self.jsonString = [cell textResult];
        }
        if (cell.tag == ExtraLoadDataTag_Method) {
            self.requestMethod = [cell textResult];
        }
    }
}

- (void)showErrorTips:(NSString *)tips {
    self.tipsLabel.textColor = [UIColor redColor];
    self.tipsLabel.text = tips;
}

- (void)sendRequest {
    NSString *urlString = self.url;
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[[NSURL alloc] initWithString:urlString]];
    NSString *parameterString = [self getRequestParamters];
    if ([self.requestMethod.lowercaseString isEqualToString:@"post"]) {
        request.HTTPMethod = @"POST";
        request.HTTPBody = [parameterString dataUsingEncoding:NSUTF8StringEncoding];
    } else {
        request.HTTPMethod = @"GET";
        request.URL = [NSURL URLWithString:[urlString stringByAppendingFormat:@"?%@", parameterString]];
    }
    self.resultTextView.text = @"请求中...";
    [NSURLConnection sendAsynchronousRequest:request queue:self.operationQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *err) {
        if (err || data.length <= 0) {
            NSLog(@"request error: %@", err.localizedDescription);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showErrorTips:err.localizedDescription];
                self.resultTextView.text = err.localizedDescription;
            });
            return;
        }
        NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"jsonString: %@", jsonString);
        dispatch_async(dispatch_get_main_queue(), ^{
            self.tipsLabel.text = @"结果拉取成功，已经复制到粘贴板！";
            self.resultTextView.text = jsonString;
            [[UIPasteboard generalPasteboard] setString:jsonString];
        });
    }];
}

- (NSString *)getRequestParamters {
    NSDictionary *extendInfo = @{};
    NSData *jsonData = [self.jsonString dataUsingEncoding:NSUTF8StringEncoding];
    if (self.jsonString.length > 0 && jsonData.length > 0) {
        NSError *error;
        extendInfo = [NSJSONSerialization JSONObjectWithData:jsonData
                                                     options:NSJSONReadingMutableContainers
                                                       error:&error];
    }
    
    NSMutableDictionary *mutableExtendInfo = [extendInfo mutableCopy];
    NSString *openId = [TencentOAuth sharedInstance].openId;
    if (openId.length > 0) {
        mutableExtendInfo[@"openid"] = openId;
    }
    NSString *accessToken = [TencentOAuth sharedInstance].accessToken;
    if (accessToken.length > 0) {
        mutableExtendInfo[@"access_token"] = accessToken;
    }
    if (self.serviceId.length > 0) {
        mutableExtendInfo[@"serviceId"] = self.serviceId;
    }
    mutableExtendInfo[@"format"] = @"json";
    
    NSString *parameterString = @"";
    for (NSString *key in mutableExtendInfo.allKeys) {
        NSString *value = mutableExtendInfo[key];
        parameterString = [parameterString stringByAppendingFormat:@"%@=%@&", key, value];
    }
    if ([parameterString rangeOfString:@"&"].location > 0) {
        parameterString = [parameterString substringToIndex:parameterString.length - 1];
    }
    return parameterString;
}

#pragma mark - Events

- (void)tapEvent:(UITapGestureRecognizer *)tap {
    [self.view endEditing:YES];
}

- (void)confirmButtonEvent:(UIButton *)sender {
    [self loadResult];
    if (self.url.length <= 0) {
        [self showErrorTips:@"URL不能为空！"];
        return;
    }
    [self sendRequest];
}

#pragma mark - UITableViewDelegate、UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.dataSource count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    ExtraLoadDataCellModel *cellModel = [self cellModelWithRow:indexPath.row];
    return [cellModel cellHeight];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ExtraLoadDataCellModel *cellModel = [self cellModelWithRow:indexPath.row];
    NSString *cellIdentifier = @"SdkExtraServiceEditCell";
    ExtraLoadDataTableCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[ExtraLoadDataTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.tag = cellModel.cellTag;
    }
    [cell loadCellWithModel:cellModel];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - Getter and setter

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.scrollEnabled = NO;
        _tableView.contentInset = UIEdgeInsetsMake(64+34, 0, 0, 0);
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
    }
    return _tableView;
}

- (UIButton *)confirmButton {
    if (!_confirmButton) {
        _confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _confirmButton.layer.cornerRadius = 6;
        _confirmButton.layer.borderWidth = 0.8f;
        _confirmButton.layer.borderColor = [UIColor grayColor].CGColor;
        _confirmButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:16];
        [_confirmButton setTitle:@"发 送 请 求" forState:UIControlStateNormal];
        [_confirmButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_confirmButton addTarget:self action:@selector(confirmButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _confirmButton;
}

- (UILabel *)tipsLabel {
    if (!_tipsLabel) {
        UILabel *tipsLabel = [[UILabel alloc] init];
        tipsLabel.textColor = [UIColor grayColor];
        tipsLabel.textAlignment = NSTextAlignmentLeft;
        tipsLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:13];
        BOOL isLogined = [TencentOAuth sharedInstance].accessToken.length > 0;
        tipsLabel.text = [@"注意：URL和参数都必须填写。" stringByAppendingFormat: isLogined ? @"\n当前已登录" : @"\n当前未登录"];
        tipsLabel.numberOfLines = 0;
        _tipsLabel = tipsLabel;
    }
    return _tipsLabel;
}

- (UITextView *)resultTextView {
    if (!_resultTextView) {
        _resultTextView = [[UITextView alloc] init];
        _resultTextView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        _resultTextView.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14.f];
        _resultTextView.layer.borderWidth = 0.5f;
        _resultTextView.layer.borderColor = [UIColor grayColor].CGColor;
        _resultTextView.layer.cornerRadius = 3.0;
        _resultTextView.layer.masksToBounds = YES;
        _resultTextView.text = @"显示结果...";
    }
    return _resultTextView;
}

- (NSOperationQueue *)operationQueue {
    if (!_operationQueue) {
        _operationQueue = [[NSOperationQueue alloc] init];
    }
    return _operationQueue;
}

@end
